"use strict"

const moment = require('moment')
module.exports = app => {
    const { STRING, DATE, INTEGER, DECIMAL, TEXT} = app.Sequelize
    const Goods = app.model.define('goods', {
        id: {
            type: INTEGER,
            autoIncrement: true,
            primaryKey: true,
        },
        title: {
            type: STRING,
            allowNull: false
        },
        img: {
            type: STRING,
            allowNull: false
        },
        new: {
            type: INTEGER,
            allowNull: false
        },
        brand_id: {
            type: INTEGER,
            allowNull: false
        },
        category_id: {
            type: STRING,
            allowNull: false,
            get() {
                return JSON.parse(this.getDataValue('category_id'))
            },
            set(val) {
                this.setDataValue('category_id', JSON.stringify(val))
            }
        },
        sales_price: {
            type: DECIMAL,
            allowNull: false,
            set(val) {                
                this.setDataValue('sales_price', val ? val : 0);
            }
        },
        price: {
            type: DECIMAL,
            allowNull: false,
            set(val) {                
                this.setDataValue('price', val ? val : '');
            }
        },
        inventory: {
            type: INTEGER,
            allowNull: false
        },
        serial_number: {
            type: STRING,
            allowNull: false
        },
        discount: {
            type: STRING,
            allowNull: false
        },
        body: {
            type: TEXT,
            allowNull: false
        },
        create_time: {
            type: DATE,
            allowNull: false,
            get() {
                return moment(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss')
            }
        },
        update_time: {
            type: DATE,
            allowNull: true,
            get() {
                return this.getDataValue('update_time')? moment(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss') : null
            }
        },
    }) 
    Goods.associate = function() {
        // 关联主图 一对多
        Goods.hasMany(app.model.GoodsImgs, {as: 'imgs', targetKey: 'id', foreignKey: 'goods_id'})
        // 关联属性 一对多
        Goods.hasMany(app.model.AttributeKey, {as: 'attributeList', targetKey: 'id', foreignKey: 'goods_id'})
        // 关联属性组合 一对多
        Goods.hasMany(app.model.GoodsSku, {as: 'goods_specs', targetKey: 'id', foreignKey: 'goods_id'})
        // 关联分类 一对一
        // Goods.belongsTo(app.model.Category, {targetKey: 'id', foreignKey: 'category_id'})
        // 关联品牌
        Goods.belongsTo(app.model.Brand, {targetKey: 'id', foreignKey: 'brand_id'})
    }
    return Goods
}